<template>
  <div class="post-list-container">
    <!-- 轮播图区域 -->
    <div class="carousel-section">
      <div id="postCarousel" class="carousel slide" data-bs-ride="carousel">
        <div class="carousel-indicators">
          <button 
            v-for="(item, index) in carouselItems" 
            :key="index"
            type="button" 
            data-bs-target="#postCarousel" 
            :data-bs-slide-to="index"
            :class="{ active: index === 0 }"
            :aria-label="`Slide ${index + 1}`"
          ></button>
        </div>
        <div class="carousel-inner">
          <div 
            v-for="(item, index) in carouselItems" 
            :key="index"
            class="carousel-item"
            :class="{ active: index === 0 }"
          >
            <div class="carousel-bg" :style="{ backgroundImage: `url(${item.image})` }"></div>
            <div class="carousel-content">
              <div class="container">
                <div class="row">
                  <div class="col-lg-8">
                    <h2 class="carousel-title">{{ item.title }}</h2>
                    <p class="carousel-description">{{ item.description }}</p>
                    <button class="btn btn-primary btn-lg rounded-pill px-4" @click="goToPost(item.id)">
                      查看详情
                    </button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <button class="carousel-control-prev" type="button" data-bs-target="#postCarousel" data-bs-slide="prev">
          <span class="carousel-control-prev-icon" aria-hidden="true"></span>
          <span class="visually-hidden">Previous</span>
        </button>
        <button class="carousel-control-next" type="button" data-bs-target="#postCarousel" data-bs-slide="next">
          <span class="carousel-control-next-icon" aria-hidden="true"></span>
          <span class="visually-hidden">Next</span>
        </button>
      </div>
    </div>

    <!-- 帖子列表区域 -->
    <div class="container py-5">
      <div class="row mb-4">
        <div class="col-12">
          <h2 class="section-title">
            <i class="bi bi-card-list me-2"></i>最新帖子
          </h2>
          <p class="text-muted">发现校园里的新鲜事</p>
        </div>
      </div>

      <!-- 帖子列表 -->
      <div class="row">
        <div 
          v-for="post in posts" 
          :key="post.id" 
          class="col-lg-6 col-xl-4 mb-4"
        >
          <div class="card post-card h-100 border-0 shadow-sm rounded-3 overflow-hidden">
            <!-- 帖子封面 -->
            <div class="post-image-container">
              <img 
                :src="post.coverImage || '/api/placeholder/300/200'" 
                :alt="post.title" 
                class="card-img-top post-image"
                @error="handleImageError"
              >
              <div class="post-badge" :class="getPostBadgeClass(post)">
                {{ getPostBadgeText(post) }}
              </div>
            </div>

            <div class="card-body d-flex flex-column">
              <h5 class="card-title post-title text-truncate">{{ post.title }}</h5>
              
              <div class="post-meta mb-3">
                <div class="d-flex justify-content-between align-items-center">
                  <div class="post-price text-success fw-bold">
                    <i class="bi bi-currency-dollar me-1"></i>
                    {{ post.price ? `¥${post.price}` : '面议' }}
                  </div>
                  <div class="post-category badge bg-primary">
                    {{ post.categoryName }}
                  </div>
                </div>
              </div>

              <div class="post-stats d-flex justify-content-between text-muted small mb-3">
                <div class="views">
                  <i class="bi bi-eye me-1"></i>
                  {{ post.viewCount || 0 }} 浏览
                </div>
                <div class="time">
                  <i class="bi bi-clock me-1"></i>
                  {{ formatDate(post.createdAt) }}
                </div>
              </div>

              <!-- 倒计时 -->
              <div v-if="post.expiredAt" class="countdown-container mb-3">
                <div class="countdown-label d-flex align-items-center">
                  <i class="bi bi-hourglass-split me-1"></i>
                  距离过期:
                </div>
                <div class="countdown-display">
                  <span class="countdown-value">{{ getTimeRemaining(post.expiredAt).days }}</span> 天 
                  <span class="countdown-value">{{ getTimeRemaining(post.expiredAt).hours }}</span> 小时 
                  <span class="countdown-value">{{ getTimeRemaining(post.expiredAt).minutes }}</span> 分钟
                </div>
              </div>

              <div class="mt-auto">
                <button 
                  class="btn btn-outline-primary w-100 rounded-pill"
                  @click="goToPostDetail(post.id)"
                >
                  查看详情
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 加载更多 -->
      <div class="row mt-4">
        <div class="col-12 text-center">
          <button 
            v-if="hasMorePosts" 
            class="btn btn-lg btn-outline-primary rounded-pill px-5"
            @click="loadMorePosts"
            :disabled="loading"
          >
            <span v-if="loading">
              <span class="spinner-border spinner-border-sm me-2" role="status"></span>
              加载中...
            </span>
            <span v-else>
              <i class="bi bi-arrow-down-circle me-2"></i>
              加载更多
            </span>
          </button>
          <div v-else class="alert alert-info">
            没有更多帖子了
          </div>
        </div>
      </div>
    </div>
  </div>
  <BackToTop>
  </BackToTop>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { getPostAllService, 
         getCategoriesListService,
         getPostCoverService,
         incrementPostViewCountService } from '@/api/post.js'
import BackToTop from '@/components/BackToTop.vue'

const router = useRouter()

// 轮播图数据
const carouselItems = ref([
  {
    id: 1,
    title: '校园二手交易',
    description: '在这里找到你想要的二手物品，让闲置物品发挥价值',
    image: 'https://picsum.photos/1200/500?random=1'
  },
  {
    id: 2,
    title: '失物招领',
    description: '帮助你找回丢失的物品，或者帮助他人找回失物',
    image: 'https://picsum.photos/1200/500?random=2'
  },
  {
    id: 3,
    title: '校园活动',
    description: '发现校园内的精彩活动，丰富你的校园生活',
    image: 'https://picsum.photos/1200/500?random=3'
  }
])

// 帖子数据
const posts = ref([])
const loading = ref(false)
const hasMorePosts = ref(true)
const currentPage = ref(1)


// 获取帖子列表
const fetchPosts = async () => {
  loading.value = true
  try {
    // 获取分类列表
    const categoriesRes = await getCategoriesListService()
    const categories = categoriesRes.data
    // 获取所有帖子
    const res = await getPostAllService()
    
    
    // 检查返回的数据结构
    let postItems = []
    if (Array.isArray(res.data)) {
      // 如果直接返回数组
      postItems = res.data
    } else if (res.data && Array.isArray(res.data.items)) {
      // 如果返回的是分页结构
      postItems = res.data.items
    } else {
      console.error('Unexpected data structure:', res.data)
      postItems = []
    }
    
    // 获取帖子封面图片
    let coverImagesRes = null
    try {
      coverImagesRes = await getPostCoverService()
    } catch (error) {
      console.error('获取封面图片失败:', error)
    }
    
    // 处理帖子数据
    const processedPosts = postItems.map(post => {
      // 添加分类名称
      const category = categories.find(cat => cat.id === post.categoryId)
      
      // 查找帖子封面
      let coverImage = null
      if (coverImagesRes && coverImagesRes.data) {
        const postImages = coverImagesRes.data.filter(img => img.postId === post.id)
        if (postImages.length > 0) {
          const firstImage = postImages[0]
          coverImage = firstImage.imageUrl.startsWith('http') 
            ? firstImage.imageUrl 
            : `http://localhost:8080${firstImage.imageUrl}`
        }
      }
      
      return {
        ...post,
        categoryName: category ? category.name : '未知分类',
        coverImage: coverImage
      }
    })
    
    // 添加到帖子列表
    posts.value = [...posts.value, ...processedPosts]
    
    // 检查是否还有更多数据 (由于是获取所有帖子，所以没有更多数据)
    hasMorePosts.value = false
    
  } catch (error) {
    console.error('获取帖子失败:', error)
  } finally {
    loading.value = false
  }
}

// 加载更多帖子
const loadMorePosts = () => {
  currentPage.value++
  fetchPosts()
}

// 获取帖子标签样式
const getPostBadgeClass = (post) => {
  if (post.isUrgent) return 'bg-danger'
  if (post.status === 'approved') return 'bg-success'
  if (post.status === 'pending') return 'bg-warning text-dark'
  if (post.status === 'rejected') return 'bg-danger'
  return 'bg-secondary'
}

// 获取帖子标签文本
const getPostBadgeText = (post) => {
  if (post.isUrgent) return '紧急'
  if (post.status === 'approved') return '已通过'
  if (post.status === 'pending') return '待审核'
  if (post.status === 'rejected') return '已拒绝'
  return '未知'
}

// 格式化日期
const formatDate = (dateString) => {
  const date = new Date(dateString)
  const now = new Date()
  const diffTime = Math.abs(now - date)
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
  
  if (diffDays === 1) return '今天'
  if (diffDays === 2) return '昨天'
  if (diffDays <= 7) return `${diffDays - 1}天前`
  return date.toLocaleDateString('zh-CN')
}

// 计算剩余时间
const getTimeRemaining = (endDate) => {
  const total = new Date(endDate) - new Date()
  const seconds = Math.floor((total / 1000) % 60)
  const minutes = Math.floor((total / 1000 / 60) % 60)
  const hours = Math.floor((total / (1000 * 60 * 60)) % 24)
  const days = Math.floor(total / (1000 * 60 * 60 * 24))
  
  return {
    total,
    days,
    hours,
    minutes,
    seconds
  }
}

// 处理图片加载错误
const handleImageError = (event) => {
  event.target.src = '/src/assets/images/封面加载失败.webp'
}

// 跳转到帖子详情
const goToPostDetail = async (postId) => {
  try {
    // 增加帖子浏览量
    await incrementPostViewCountService(postId)
    // 跳转到详情页
    router.push(`/post/detail/${postId}`)
  } catch (error) {
    console.error('增加浏览量失败:', error)
    // 即使增加浏览量失败，也仍然跳转到详情页
    router.push(`/post/detail/${postId}`)
  }
}

// 跳转到指定帖子
const goToPost = (postId) => {
  if (postId) {
    router.push(`/post/detail/${postId}`)
  }
}

// 初始化数据
onMounted(() => {
  fetchPosts()
})
</script>

<style scoped>
.carousel-section {
  position: relative;
  margin-bottom: 2rem;
}

.carousel-bg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-size: cover;
  background-position: center;
  filter: brightness(0.7);
}

.carousel-content {
  position: relative;
  z-index: 1;
  padding: 5rem 0;
  color: white;
}

.carousel-title {
  font-size: 2.5rem;
  font-weight: 700;
  margin-bottom: 1rem;
  text-shadow: 0 2px 4px rgba(0,0,0,0.5);
}

.carousel-description {
  font-size: 1.2rem;
  margin-bottom: 2rem;
  text-shadow: 0 1px 2px rgba(0,0,0,0.5);
  max-width: 600px;
}

.section-title {
  font-weight: 700;
  color: #333;
  position: relative;
  padding-bottom: 10px;
}

.section-title::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  width: 50px;
  height: 3px;
  background-color: #0d6efd;
  border-radius: 3px;
}

.post-card {
  transition: all 0.3s ease;
  height: 100%;
}

.post-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0,0,0,0.1) !important;
}

.post-image-container {
  position: relative;
  height: 200px;
  overflow: hidden;
}

.post-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.post-card:hover .post-image {
  transform: scale(1.05);
}

.post-badge {
  position: absolute;
  top: 10px;
  right: 10px;
  padding: 5px 10px;
  border-radius: 20px;
  font-size: 0.8rem;
  font-weight: 500;
}

.post-title {
  font-weight: 600;
  margin-bottom: 1rem;
}

.post-price {
  font-size: 1.2rem;
}

.countdown-container {
  background-color: #f8f9fa;
  border-radius: 10px;
  padding: 10px;
}

.countdown-label {
  font-size: 0.9rem;
  margin-bottom: 5px;
}

.countdown-display {
  font-size: 0.9rem;
}

.countdown-value {
  font-weight: 700;
  color: #0d6efd;
}

@media (max-width: 768px) {
  .carousel-title {
    font-size: 2rem;
  }
  
  .carousel-description {
    font-size: 1rem;
  }
  
  .carousel-content {
    padding: 3rem 0;
  }
  
  .post-image-container {
    height: 180px;
  }
}
</style>
